//
//  UIImage+Extensions.swift
//  MYDoctor
//
//  Created by Denny on 2024/3/10.
//

import UIKit

 extension UIImage {
     static func image(with color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
            let rect = CGRect(origin: .zero, size: size)
            UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
            color.setFill()
            UIRectFill(rect)
            let image = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return image
        }
     
     func compressImage(maxSize: Int) -> Data? {
         var compression: CGFloat = 1.0
         let maxCompression: CGFloat = 0.1
         let targetSize = CGSize(width: 1024, height: 1024)
         var imageData = self.jpegData(compressionQuality: compression)
         var imageSize = imageData?.count ?? 0
         var sizeExceeded = imageSize > maxSize
         
         while sizeExceeded && compression > maxCompression {
             compression -= 0.1
             imageData = self.jpegData(compressionQuality: compression)
             imageSize = imageData?.count ?? 0
             sizeExceeded = imageSize > maxSize
             
         }
         if let imageSource = CGImageSourceCreateWithData(imageData! as CFData, nil) {
             let options: [CFString: Any] = [
                kCGImageSourceThumbnailMaxPixelSize: max(targetSize.width, targetSize.height) * scale,
                kCGImageSourceCreateThumbnailFromImageAlways: true,
                kCGImageSourceCreateThumbnailWithTransform: true
             ]
             
             if let scaledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary) {
                 if let scaledImageData = UIImage(cgImage: scaledImage).jpegData(compressionQuality: compression) {
                     imageData = scaledImageData
                 }
             }
         }
         
         return imageData
     }

}
